package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @description: 登录功能
 * @author: chengbaiyi
 * @create: 2022-05-17 22:09
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int data = 0;
        String msg = "未知错误";
        // 1.得到前端数据，并进行非空校验
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (!StrUtil.isBlank(username) && !StrUtil.isBlank(password)) {
            // 2.查询数据库
            // 2.1 得到连接
            Connection connection = DBUtils.getConnection();
            // 2.2 拼接sql,得到执行器
            String sql = "select * from userinfo where username=? and password=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, SecureUtil.md5(password));
            // 2.3 执行sql
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                UserInfo userInfo = new UserInfo();
                userInfo.setUid(resultSet.getInt("uid"));
                userInfo.setUsername(resultSet.getString("username"));
                userInfo.setPassword(resultSet.getString("password"));
                userInfo.setNickname(resultSet.getString("nickname"));
                userInfo.setImg(resultSet.getString("img"));
                userInfo.setGit(resultSet.getString("git"));
                userInfo.setState(resultSet.getInt("state"));
                // 将当前登录用户保存到 session
                HttpSession session = req.getSession(true);
                if (session != null) {
                    session.setAttribute(AppVar.SESSION_USERINFO_KEY, userInfo);
                }
                data = 1;
            } else {
                msg = "用户名或密码错误！";
            }
            // 2.4 关闭资源
            DBUtils.close(resultSet, statement, connection);
        } else {
            msg = "非法参数！";
        }
        // 3.将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200, data, msg)));
    }
}
